package org.angelica.aliyun.manager;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.BasicSessionCredentials;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.imm.model.v20170906.*;
import com.aliyuncs.profile.DefaultProfile;
import org.angelica.aliyun.entity.StsToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 智能媒体管理服务
 * @author aizhimin
 */
public class ImmManager {
    private static final Logger logger = LoggerFactory.getLogger(ImmManager.class);

    private static ImmManager instance = new ImmManager();
    private ImmManager(){ }
    private static StsToken immStsToken = null;
    private static IAcsClient client = null;
    public static ImmManager getInstance(StsToken stsToken){
        //token过期，则重新创建 IMMClient
        if(immStsToken != null && !immStsToken.getSecurityToken().equals(stsToken.getSecurityToken())){
            client = null;
        }
        if(client == null){
            immStsToken = stsToken;
            BasicSessionCredentials credentials = new BasicSessionCredentials(
                    stsToken.getAccessKeyId(),
                    stsToken.getAccessKeySecret(),
                    stsToken.getSecurityToken()
            );
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou");
            client = new DefaultAcsClient(profile,credentials);
        }
        return instance;
    }

    /**
     * 同步转换文件为图片
     * @param project
     * @param srcUri
     * @param tgtType
     * @param tgtUri
     * @return
     */
    public Integer convertOfficeFormat(String project,String srcUri,String tgtType,String tgtUri){
        try {
            ConvertOfficeFormatRequest convertOfficeFormatRequest = new ConvertOfficeFormatRequest();
            convertOfficeFormatRequest.setProject(project);
            convertOfficeFormatRequest.setSrcUri(srcUri);
            convertOfficeFormatRequest.setTgtType(tgtType);
            convertOfficeFormatRequest.setTgtUri(tgtUri);
            ConvertOfficeFormatResponse convertOfficeFormatResponse = client.getAcsResponse(convertOfficeFormatRequest);
            return convertOfficeFormatResponse.getPageCount() == null ? 0 : convertOfficeFormatResponse.getPageCount();
        } catch (ClientException e) {
            logger.error(e.getMessage());
            return 0;
        }
    }

    /**
     * 异步转换文件为图片
     * @param project
     * @param srcUri
     * @param tgtType
     * @param tgtUri
     * @return
     */
    public boolean asyncConvertOfficeFormat(String project,String srcUri,String tgtType,String tgtUri){
        try {
            CreateOfficeConversionTaskRequest req = new CreateOfficeConversionTaskRequest();
            req.setProject(project);
            req.setSrcUri(srcUri);
            req.setTgtType(tgtType);
            req.setTgtUri(tgtUri);
            CreateOfficeConversionTaskResponse res = client.getAcsResponse(req);

            String taskId = res.getTaskId();
            GetOfficeConversionTaskRequest getOfficeConversionTaskRequest = new GetOfficeConversionTaskRequest();
            getOfficeConversionTaskRequest.setProject(project);
            getOfficeConversionTaskRequest.setTaskId(taskId);
            int maxCount = 30;
            int count = 0;
            while (true) {
                Thread.sleep(1000);
                GetOfficeConversionTaskResponse getOfficeConversionTaskResponse = client.getAcsResponse(getOfficeConversionTaskRequest);
                if ("Finished".equals(getOfficeConversionTaskResponse.getStatus())) {
                    return true;
                }
                if ("Failed".equals(getOfficeConversionTaskResponse.getStatus())) {
                    logger.error("转换出错，taskId={},code={}",getOfficeConversionTaskResponse.getTaskId(),getOfficeConversionTaskResponse.getFailDetail().getCode());
                    break;
                }
                count = count + 1;
                if(count >= maxCount) {
                    logger.error("OfficeConversion Timeout for 30 seconds");
                    break;
                }
            }
        } catch (ClientException e) {
            logger.error(e.getMessage());
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

}
